<template>
    <div>
        <v-list-item @click="handleSelect" :active="isSelected" :style="{ paddingLeft: (level * 20 + 16) + 'px' }"
            class="perms-item">
            <template #prepend>
                <v-btn v-if="hasChildren" :icon="isExpanded ? 'mdi-chevron-down' : 'mdi-chevron-right'" variant="text"
                    size="small" @click="handleExpand" />
                <div v-else style="width: 40px;"></div>
            </template>

            <template #title>
                <div class="d-flex align-center">
                    <v-icon :icon="getIcon(item.type)" color="primary" size="small" class="mr-2" />
                    {{ item.name }}
                </div>
            </template>

            <template #append>
                <v-checkbox :model-value="isSelected" color="primary" hide-details density="compact" @click.stop
                    @update:model-value="handleSelect" />
            </template>
        </v-list-item>

        <!-- 递归渲染子节点 -->
        <template v-if="isExpanded && hasChildren">
            <PermsListItem v-for="child in item.children" :key="child.id" :item="child" :level="level + 1"
                :selected-ids="selectedIds" :expanded-nodes="expandedNodes"
                @toggle-select="(nodeId, isSelected) => $emit('toggle-select', nodeId, isSelected)"
                @toggle-expand="(nodeId) => $emit('toggle-expand', nodeId)" />
        </template>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

interface PermsNode {
    id: string;
    name: string;
    type: string;
    children?: PermsNode[];
    [key: string]: any;
}

interface Props {
    item: PermsNode;
    level: number;
    selectedIds: Set<string>;
    expandedNodes: Set<string>;
}

const props = defineProps<Props>();
const emit = defineEmits<{
    'toggle-select': [nodeId: string, isSelected: boolean];
    'toggle-expand': [nodeId: string];
}>();

const isSelected = computed(() => props.selectedIds.has(props.item.id));
const isExpanded = computed(() => props.expandedNodes.has(props.item.id));
const hasChildren = computed(() => props.item.children && props.item.children.length > 0);

const handleSelect = () => {
    emit('toggle-select', props.item.id, !isSelected.value);
};

const handleExpand = (e: Event) => {
    e.stopPropagation();
    if (hasChildren.value) {
        emit('toggle-expand', props.item.id);
    }
};

// 获取图标
function getIcon(type: string) {
    switch (type) {
        case '1': return 'mdi-view-dashboard';
        case '2': return 'mdi-cog';
        case '3': return 'mdi-link';
        default: return 'mdi-file-document-outline';
    }
}
</script>

<style lang="scss" scoped>
.perms-item {
    min-height: 40px;

    &:hover {
        background-color: rgba(0, 0, 0, 0.04);
    }

    &.v-list-item--active {
        background-color: rgba(25, 118, 210, 0.1);
    }
}
</style>